import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:merchants/providers/providers.dart';
import 'package:shared_preferences/shared_preferences.dart';

class PushManager {
  static const MethodChannel _pushChannel = MethodChannel(
    'com.shopthrive.merchants/push',
  );
  static final GlobalKey<ScaffoldMessengerState> scaffoldMessengerKey =
  GlobalKey<ScaffoldMessengerState>();
  static const List<String> _supportedBrands = [
    'vivo',
    'huawei',
    'honor',
    'xiaomi',
    'oppo',
  ];

  static Future<void> init(ProviderContainer container) async {
    _pushChannel.setMethodCallHandler((call) async {
      switch (call.method) {
        case 'onPushToken':
          final Map<dynamic, dynamic> params = call.arguments;
          final String brand = params['brand'] ?? '';
          if (params.containsKey('token')) {
            final String token = params['token'];
            await _uploadToken(brand, token, container);
          } else if (params.containsKey('errorCode')) {
            final int errorCode = params['errorCode'];
            print('$brand push token error: $errorCode');
            String message = '获取 $brand 推送 ID 失败，错误码: $errorCode';
            if (errorCode == -4) {
              message = '请在系统设置中开启 $brand 推送权限';
            } else if (errorCode == -7) {
              message = '$brand 推送功能暂未支持，请稍后重试';
            } else if (errorCode == -8) {
              message = '打开网页失败，请检查网络';
            }
            scaffoldMessengerKey.currentState?.showSnackBar(
              SnackBar(
                content: Text(message),
                action: errorCode == -4
                    ? SnackBarAction(
                  label: '去设置',
                  onPressed: () {
                    // TODO: 打开系统设置
                  },
                )
                    : null,
              ),
            );
          }
          break;
        case 'onMessage':
          final Map<dynamic, dynamic> data = call.arguments;
          final String route = data['route']?.toString() ?? '/tabs/orders';
          final Map<String, dynamic> params = Map<String, dynamic>.from(
            data['params'] ?? {},
          );
          final int skipType = data['skipType'] is int ? data['skipType'] : -1;
          print(
            'Received push message: route=$route, params=$params, skipType=$skipType',
          );
          if (skipType != 2) {
            scaffoldMessengerKey.currentState?.showSnackBar(
              SnackBar(
                content: Text('新消息: ${params['title'] ?? '点击查看详情'}'),
                action: SnackBarAction(label: '查看', onPressed: () {}),
              ),
            );
          }
          break;
      }
      return null;
    });
  }

  static Future<void> requestPushToken({
    String brand = 'vivo',
    bool forceRefresh = false,
  }) async {
    if (!_supportedBrands.contains(brand)) {
      print('Unsupported brand: $brand');
      scaffoldMessengerKey.currentState?.showSnackBar(
        SnackBar(content: Text('$brand 不支持推送')),
      );
      return;
    }
    try {
      await _pushChannel.invokeMethod('requestPushToken', {
        'brand': brand,
        'forceRefresh': forceRefresh,
      });
      print('Requested push token for $brand, forceRefresh: $forceRefresh');
    } catch (e) {
      print('Failed to request push token for $brand: $e');
      scaffoldMessengerKey.currentState?.showSnackBar(
        SnackBar(content: Text('请求 $brand 推送 ID 失败')),
      );
    }
  }

  static Future<void> _uploadToken(String brand, String token, ProviderContainer container) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final lastToken = prefs.getString('${brand}_token');
      if (lastToken == token) {
        print('$brand token unchanged, skipping upload');
        return;
      }

      final auth = container.read(authProvider);
      final unionid = auth.userInfo?.unionid;
      if (unionid == null || unionid.isEmpty) {
        scaffoldMessengerKey.currentState?.showSnackBar(
          const SnackBar(content: Text('未找到用户标识，无法上传推送 ID')),
        );
        return;
      }

      final merchantUserService = container.read(merchantUserServiceProvider);
      await merchantUserService.uploadPushToken(
        token: token,
        brand: brand,
        unionid: unionid,
      );

      await prefs.setString('${brand}_token', token);
      await prefs.setInt(
        '${brand}_upload_timestamp',
        DateTime.now().millisecondsSinceEpoch,
      );
    } catch (e) {
      scaffoldMessengerKey.currentState?.showSnackBar(
        SnackBar(content: Text('上传 $brand 推送 ID 出错')),
      );
    }
  }

  static Future<String> _getDeviceId() async {
    return 'device_${DateTime.now().millisecondsSinceEpoch}';
  }

  static void handleInitialNotification(BuildContext context) {
    _pushChannel.invokeMethod('getInitialNotification').then((data) {
      if (data != null) {
        print('Initial Notification Data: $data');
        final String route = data.toString();
        _handleMessageNavigation(context, route, {});
      }
    });
  }

  static void _handleMessageNavigation(
      BuildContext context,
      String route,
      Map<String, dynamic> params,
      ) {
    try {
      if (route.isEmpty) {
        print('Invalid route: empty');
        return;
      }
      final goRouter = GoRouter.of(context);
      print('Navigating to route: $route with params: $params');
      goRouter.push(route, extra: params);
    } catch (e) {
      print('Navigation error: $e');
      scaffoldMessengerKey.currentState?.showSnackBar(
        SnackBar(content: Text('跳转失败: $e')),
      );
    }
  }
}